package com.leqicheng.tenon.share;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.cordova.CallbackContext;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.leqicheng.tenon.RuntimeActivity;
import com.leqicheng.tenon.R;
import com.leqicheng.tenon.login.PopWindow;
import com.leqicheng.tenon.login.WeiboLoginHttpRequest;
import com.leqicheng.tenon.login.WeixinLoginHttpRequest;
import com.leqicheng.tenon.login.weibo.AccessTokenKeeper;
import com.leqicheng.tenon.login.weibo.AuthListener;
import com.leqicheng.tenon.login.weibo.WeiboConstants;
import com.leqicheng.tenon.login.weixin.WeixinConstants;
import com.leqicheng.tenon.model.EntryInfoModel;
import com.leqicheng.tenon.pay.alipay.AlipayConstant;
import com.leqicheng.tenon.pay.alipay.ChargeAliPayHttpRequest;
import com.leqicheng.tenon.pay.alipay.PayResult;
import com.leqicheng.tenon.pay.weixin.ChargeWeixinHttpRequest;
import com.leqicheng.tenon.util.GeneralCallBack;
import com.leqicheng.tenon.util.MD5;
import com.leqicheng.tenon.util.OrientationEnum;
import com.leqicheng.tenon.util.RequestStatus;
import com.leqicheng.tenon.util.RequestTypeEnum;
import com.leqicheng.tenon.util.SignUtils;
import com.leqicheng.tenon.util.WindowStatusCode;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class PopShareWindow extends PopWindow implements OnClickListener,
        GeneralCallBack {
    private CallbackContext mCallbackContext;
    private Context mContext;
    private PopShareWindow mPopWindowContext;
    private Handler mHandler;
    private LayoutInflater inflater;
    private PopupWindow mPopupWindow;
    private ImageButton mCloseWindowButton;
    private EntryInfoModel entryInfoModel;
    private RelativeLayout mShareToWeiboButton;
    private IWeiboShareAPI mWeiboShareAPI;
    private IWXAPI wxApi;
    private RelativeLayout mShareToWeixinButton;
    private RelativeLayout mShareToWeixinCircleButton;
    private ShareInfoModel model;
    private LinearLayout mLayoutParent;

    public PopShareWindow(Handler handler, Context context,
            OrientationEnum orientationEnum, CallbackContext callbackContext,
            org.json.JSONArray data) {
        super();
        mCallbackContext = callbackContext;
        this.mContext = context;
        mPopWindowContext = this;
        mHandler = handler;

        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mContext,
                WeiboConstants.APP_KEY);
        this.inflater = (LayoutInflater) this.mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = this.inflater.inflate(R.layout.popwindow_share, null);
        this.mLayoutParent = (LinearLayout) layout
                .findViewById(R.id.parent_layout);
        mCloseWindowButton = (ImageButton) layout
                .findViewById(R.id.close_window);
        mCloseWindowButton.setOnClickListener(this);
        // mShareToWeiboButton = (RelativeLayout) layout
        // .findViewById(R.id.share_to_weibo);
        // mShareToWeiboButton.setOnClickListener(this);
        mShareToWeixinButton = (RelativeLayout) layout
                .findViewById(R.id.share_to_wechat);
        mShareToWeixinButton.setOnClickListener(this);
        mShareToWeixinCircleButton = (RelativeLayout) layout
                .findViewById(R.id.share_to_wechat_circle);
        mShareToWeixinCircleButton.setOnClickListener(this);

        // this.mPopupWindow = new PopupWindow(layout,
        // LayoutParams.WRAP_CONTENT,
        // LayoutParams.WRAP_CONTENT);
        this.mPopupWindow = new PopupWindow(layout);
        this.mPopupWindow.setFocusable(true);
        // 控制popupwindow的宽度和高度自适应
        this.mLayoutParent.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        this.mPopupWindow.setWidth(this.mLayoutParent.getMeasuredWidth() + 6);
        this.mPopupWindow.setHeight(this.mLayoutParent.getMeasuredHeight() + 6);

        createShareModel(data);

        // 实例化
        wxApi = WXAPIFactory.createWXAPI(context, WeixinConstants.APP_ID);
        wxApi.registerApp(WeixinConstants.APP_ID);

        // this.mPopupWindow.setWidth(this.mLayoutParent.getMeasuredWidth() +
        // 6);
        // this.mPopupWindow.setHeight(this.mLayoutParent.getMeasuredHeight() +
        // 6);

        // this.mPopupWindow.setBackgroundDrawable(this.mContext.getResources()
        // .getDrawable(R.drawable.boder));
        // 控制popupwindow点击屏幕其他地方消失
        // this.mPopupWindow.setOutsideTouchable(false);//
        // // 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
    }

    private void createShareModel(org.json.JSONArray data) {
        model = ShareInfoModel.getInstance();
        if (data != null) {
            String mShareDataInString = data.toString();
            JSONArray shareDataInJson = JSON.parseArray(mShareDataInString);
            JSONObject shareDataInJsonObj = shareDataInJson.getJSONObject(0);
            model.setShareDescription(shareDataInJsonObj
                    .getString("description"));
            model.setShareTitle("我在“"
                    + EntryInfoModel.getInstance().getChannelName() + "”里玩"
                    + EntryInfoModel.getInstance().getGameName() + "。"
                    + shareDataInJsonObj.getString("title"));
            model.setShareGameIconUrl(EntryInfoModel.getInstance()
                    .getGameIconUrl());
            // -------------------------------------------------
            model.setShareUrl(EntryInfoModel.getInstance().getShareUrl());
        } else {
            if (EntryInfoModel.getInstance().getGameName() != null) {
                model.setShareTitle("我在“"
                        + EntryInfoModel.getInstance().getChannelName() + "”里玩"
                        + EntryInfoModel.getInstance().getGameName()
                        + "，快来一起玩吧~");
            } else {
                model.setShareTitle("我在“"
                        + EntryInfoModel.getInstance().getChannelName()
                        + "”里玩游戏" + "，快来一起玩吧~");
            }
            model.setShareDescription(" ");
            model.setShareGameIconUrl(EntryInfoModel.getInstance()
                    .getGameIconUrl());
            if (EntryInfoModel.getInstance().getShareUrl() != null) {
                model.setShareUrl(EntryInfoModel.getInstance().getShareUrl());
            }
        }

    }

    public PopupWindow getPopupWindow() {
        return this.mPopupWindow;
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.share_to_wechat) {
            registerWeixinBroadcast();
            wechatShare(0);
        } else if (v.getId() == R.id.share_to_wechat_circle) {
            registerWeixinBroadcast();
            wechatShare(1);
        } else if (v.getId() == R.id.close_window) {
            Message msg = new Message();
            msg.what = WindowStatusCode.SHARE_WINDOW_SUCCEED;
            mHandler.sendMessage(msg);
        }
    }

    private void registerWeiboBroadcast() {
        if (mCallbackContext == null) {
            return;
        }
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("weibo share complete"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mContext.unregisterReceiver(this);
                Message msg = new Message();
                msg.what = WindowStatusCode.SHARE_WINDOW_SUCCEED;
                mHandler.sendMessage(msg);
                if (intent.getBooleanExtra("share_status", false)) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put("status", "OK");
                    org.json.JSONObject resultInJson = new org.json.JSONObject(
                            result);
                    if (mCallbackContext != null) {
                        mCallbackContext.success(resultInJson);
                    }
                }
            }
        };
        mContext.registerReceiver(myBroadcastReceiver, intentFilter); // 注册监听
    }

    private void registerWeixinBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("weixin share complete"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mContext.unregisterReceiver(this);
                Message msg = new Message();
                msg.what = WindowStatusCode.SHARE_WINDOW_SUCCEED;
                mHandler.sendMessage(msg);
                if (intent.getBooleanExtra("share_status", false)) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put("status", "OK");
                    org.json.JSONObject resultInJson = new org.json.JSONObject(
                            result);
                    if (mCallbackContext != null) {
                        mCallbackContext.success(resultInJson);
                    }
                }
            }
        };
        mContext.registerReceiver(myBroadcastReceiver, intentFilter); // 注册监听
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = getSharedText();
        return textObject;
    }

    private String getSharedText() {
        String ShareText = "";
        if (model.getShareTitle() != null) {
            ShareText = ShareText + model.getShareTitle();
        }
        if (model.getShareDescription() != null) {
            ShareText = ShareText + model.getShareDescription();
        }
        if (model.getShareUrl() != null) {
            ShareText = ShareText + model.getShareUrl();
        }
        return ShareText;

        // int formatId = R.string.weibosdk_demo_share_text_template;
        // String format = getString(formatId);
        // String text = format;
        // String demoUrl = getString(R.string.weibosdk_demo_app_url);
        // if (mTextCheckbox.isChecked() || mImageCheckbox.isChecked()) {
        // format = getString(R.string.weibosdk_demo_share_text_template);
        // }
        // if (mShareWebPageView.isChecked()) {
        // format = getString(R.string.weibosdk_demo_share_webpage_template);
        // text = String.format(format,
        // getString(R.string.weibosdk_demo_share_webpage_demo),
        // demoUrl);
        // }
        // if (mShareMusicView.isChecked()) {
        // format = getString(R.string.weibosdk_demo_share_music_template);
        // text = String
        // .format(format,
        // getString(R.string.weibosdk_demo_share_music_demo),
        // demoUrl);
        // }
        // if (mShareVideoView.isChecked()) {
        // format = getString(R.string.weibosdk_demo_share_video_template);
        // text = String
        // .format(format,
        // getString(R.string.weibosdk_demo_share_video_demo),
        // demoUrl);
        // }
        // if (mShareVoiceView.isChecked()) {
        // format = getString(R.string.weibosdk_demo_share_voice_template);
        // text = String
        // .format(format,
        // getString(R.string.weibosdk_demo_share_voice_demo),
        // demoUrl);
        // }
        // return text;
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 当{@link IWeiboShareAPI#getWeiboAppSupportAPI()} < 10351 时，只支持分享单条消息，即
     * 文本、图片、网页、音乐、视频中的一种，不支持Voice消息。
     * @param hasText
     *            分享的内容是否有文本
     * @param hasImage
     *            分享的内容是否有图片
     * @param hasWebpage
     *            分享的内容是否有网页
     * @param hasMusic
     *            分享的内容是否有音乐
     * @param hasVideo
     *            分享的内容是否有视频
     */
    private void sendSingleMessage(boolean hasText, boolean hasImage,
            boolean hasWebpage, boolean hasMusic, boolean hasVideo) {

        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
        if (hasText) {
            weiboMessage.mediaObject = getTextObj();
        }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
        // if (hasWebpage) {
        // weiboMessage.mediaObject = getWebpageObj();
        // }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
        /*
         * if (hasVoice) {
         * weiboMessage.mediaObject = getVoiceObj();
         * }
         */

        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest((Activity) mContext, request);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 注意：当 {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351
     * 时，支持同时分享多条消息，
     * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
     * @param hasText
     *            分享的内容是否有文本
     * @param hasImage
     *            分享的内容是否有图片
     * @param hasWebpage
     *            分享的内容是否有网页
     * @param hasMusic
     *            分享的内容是否有音乐
     * @param hasVideo
     *            分享的内容是否有视频
     * @param hasVoice
     *            分享的内容是否有声音
     */
    private void sendMultiMessage(boolean hasText, boolean hasImage,
            boolean hasWebpage, boolean hasMusic, boolean hasVideo,
            boolean hasVoice) {

        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        if (hasText) {
            weiboMessage.textObject = getTextObj();
        }

        // if (hasImage) {
        // weiboMessage.imageObject = getImageObj();
        // }
        //
        // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
        // if (hasWebpage) {
        // weiboMessage.mediaObject = getWebpageObj();
        // }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
        // if (hasVoice) {
        // weiboMessage.mediaObject = getVoiceObj();
        // }

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest((Activity) mContext, request);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage}
     */
    private void sendMessage(boolean hasText, boolean hasImage,
            boolean hasWebpage, boolean hasMusic, boolean hasVideo,
            boolean hasVoice) {

        // if (mShareType == SHARE_CLIENT) {
        if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
            int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
            if (supportApi >= 10351 /* ApiUtils.BUILD_INT_VER_2_2 */) {
                sendMultiMessage(hasText, hasImage, hasWebpage, hasMusic,
                        hasVideo, hasVoice);
            } else {
                sendSingleMessage(hasText, hasImage, hasWebpage, hasMusic,
                        hasVideo/* , hasVoice */);
            }
        } else {
            Toast.makeText(mContext, "微博客户端不支持 SDK 分享或微博客户端未安装或微博客户端是非官方版本。",
                    Toast.LENGTH_SHORT).show();
        }
        // } else if (mShareType == SHARE_ALL_IN_ONE) {
        // sendMultiMessage(hasText, hasImage, hasWebpage, hasMusic, hasVideo,
        // hasVoice);
        // }
    }

    /**
     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
     * @param flag
     *            (0:分享到微信好友，1：分享到微信朋友圈)
     */
    private void wechatShare(final int flag) {
        WXWebpageObject webpage = new WXWebpageObject();
        model = ShareInfoModel.getInstance();
        webpage.webpageUrl = model.getShareUrl();
        final WXMediaMessage msg = new WXMediaMessage(webpage);

        msg.title = model.getShareTitle();
        msg.description = model.getShareDescription();
        if (mCallbackContext != null) {
            // 这里替换一张自己工程里的图片资源
            ImageSize mImageSize = new ImageSize(150, 150);
            Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
                    model.getShareGameIconUrl(), mImageSize);
            // Bitmap thumb =
            // BitmapFactory.decodeResource(mContext.getResources(),
            // R.drawable.tenon_share_wechat_circle);
            msg.setThumbImage(bitmap);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                    : SendMessageToWX.Req.WXSceneTimeline;
            wxApi.sendReq(req);
        } else {
            ImageSize mImageSize = new ImageSize(150, 150);
            ImageLoader.getInstance().loadImage(model.getShareGameIconUrl(),
                    mImageSize, new ImageLoadingListener() {

                        @Override
                        public void onLoadingStarted(String arg0, View arg1) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onLoadingFailed(String arg0, View arg1,
                                FailReason arg2) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onLoadingComplete(String arg0, View arg1,
                                Bitmap arg2) {
                            // TODO Auto-generated method stub
                            msg.setThumbImage(arg2);

                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = String.valueOf(System
                                    .currentTimeMillis());
                            req.message = msg;
                            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                                    : SendMessageToWX.Req.WXSceneTimeline;
                            wxApi.sendReq(req);
                        }

                        @Override
                        public void onLoadingCancelled(String arg0, View arg1) {
                            // TODO Auto-generated method stub

                        }
                    });
        }
    }
}
